package com.al.el;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@WebServlet(urlPatterns = "/user")
public class UserServlet extends HttpServlet{
	//想要在静态代码块中初始化就需要加 static 关键字
	private static Map<Integer,User> map = new HashMap<>();
	
	//也可以加到它的无参构造函数中，反射机制创建的时候进行初始化
	static {
		map.put(1,new User(1,"张三",88.3));
		map.put(2,new User(2,"李四",78.2));
		map.put(3,new User(3,"小喵", 96.4));
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//这个一模块完成了添加和修改，传过来 id 不存在就是添加
		//id 已存在就是修改（修改的时候不能修改 id）
		req.setCharacterEncoding("UTF-8");
		String idStr = req.getParameter("id");
		String name = req.getParameter("name");
		String scoreStr = req.getParameter("score");
		Integer id = Integer.parseInt(idStr);
		Double score = Double.parseDouble(scoreStr);
		User user = new User(id, name, score);
		map.put(id,user);
		resp.sendRedirect("/myjsp003/user");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if(method == null) {
			method = "findAll";
		}
		switch(method) {
		case "findAll":
			req.setAttribute("map", map.values());
			req.getRequestDispatcher("index.jsp").forward(req, resp);
			break;
		case "delete":
			String idStr = req.getParameter("id");
			Integer id = Integer.parseInt(idStr);
			map.remove(id);
			//删完还要展示，可以选择把上面的代码粘下来，但是重复了，我们可以重
			//定向到/user 使其进行查询逻辑
			resp.sendRedirect("/myjsp003/user");
			break;
		case "getById":
			idStr = req.getParameter("id");
			id = Integer.parseInt(idStr);
			req.setAttribute("user", map.get(id));
			req.getRequestDispatcher("update.jsp").forward(req, resp);
			break;
		}
	}
}
